package com.qiu.greened.ui.my

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.widget.Toast
import androidx.core.content.edit
import androidx.lifecycle.lifecycleScope
import com.qiu.greened.MainActivity
import com.qiu.greened.bean.UserPostBean
import com.qiu.greened.databinding.ActivityLoginBinding
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.network.UserService
import com.qiu.greened.utils.MyData
import kotlinx.coroutines.launch

/**
 * 登录页
 */
class LoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //标题栏
        supportActionBar?.let {
            it.setHomeButtonEnabled(true)
            it.setDisplayHomeAsUpEnabled(true)
            it.title = "登录"
        }
        //登录按钮
        binding.btnLogin.setOnClickListener {
            val phone: String = binding.editPhone.text.toString()
            val password: String = binding.editPassword.text.toString()
            binding.editLayoutPhone.error = when {
                phone == "" -> "手机号不能为空"
                phone.length < 11 -> "请输入正确的手机号"
                else -> null
            }
            binding.editLayoutPassword.error = when (password) {
                "" ->  "密码不能为空"
                else ->  null
            }
            if (binding.editLayoutPhone.error == null && binding.editLayoutPassword.error == null) {
                login(phone, password)
            }

        }
        binding.btnRegister.setOnClickListener {
            startActivity(Intent(this, RegisterActivity::class.java))
        }
    }

    //登录
    private fun login(phone:String, password:String) {
        lifecycleScope.launch {
            try {
                val data = ServiceCreator.create<UserService>()
                    .getUserLoginData(UserPostBean(phone,password)).dataConvert()
                getSharedPreferences("data", Context.MODE_PRIVATE).edit {
                    putString("phone", phone)
                    putString("password", password)
                    putInt("userId", data.userId)
                    putString("userName", data.userName)
                    putString("userAvatar", data.userAvatar)
                    putString("token", data.token)
                }
                MyData.setLoginData()
                startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                finish()
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(applicationContext, "${e.message}", Toast.LENGTH_SHORT).show()
                Log.i("请求失败", "${e.message}")
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish() // back button
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}